package carassius.GUI;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;

/**
 *
 * @author siebz0r
 */
public class TextFieldWithMenu
		extends JTextField
{
	private final CopyPastePopupMenu popupMenu;

	public TextFieldWithMenu()
	{
		popupMenu = new CopyPastePopupMenu();
		add(popupMenu);

		getKeymap().addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_CONTEXT_MENU, 0), new AbstractAction()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				showPopupMenu();
			}
		});
	}

	private void showPopupMenu()
	{
		try
		{
			Rectangle caret = modelToView(getCaretPosition());
			popupMenu.show(getParent(), caret.x + caret.width, caret.y + caret.height);
		}
		catch (BadLocationException ex)
		{
			System.out.println("Couldn't get caret location!");
		}
	}

	@Override
	protected void processMouseEvent(MouseEvent e)
	{
		if (e.getID() == MouseEvent.MOUSE_CLICKED && e.getButton() == MouseEvent.BUTTON3)
		{
			int caret = viewToModel(new Point(getMousePosition().x, getMousePosition().y));
			getCaret().setDot(caret);
			showPopupMenu();
		}
		else
		{
			super.processMouseEvent(e);
		}
	}
}